package com.share.wechat.core.service.impl;

import com.share.common.tools.ID.IDutils;
import com.share.wechat.core.config.constant.CategoryConfig;
import com.share.wechat.core.entity.Category;
import com.share.wechat.core.repository.inter.CategoryRepository;
import com.share.wechat.core.service.CategoryService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 实现类
 * Created by er on 2017/11/17.
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    private Logger logger = Logger.getLogger(this.getClass());
    @Autowired
    private CategoryRepository categoryRepository;

    @Override
    public void insertOne(Category category) {
        if (StringUtils.isEmpty(category.getId())) {
            category.setId(IDutils.getUUIDNoLine());
        }
        logger.info("插入一个对象Category" + category);
        categoryRepository.save(category);
    }

    @Override
    public void updateOne(Category category) {
        if (StringUtils.isEmpty(category.getId())) {
            logger.info("未查询到该信息 更新失败");
            return;
        }
        categoryRepository.save(category);
    }

    @Override
    public Category selectOne(String id) {
        if (StringUtils.isEmpty(id)) {
            logger.info("id不能为空 查询失败");
            return null;
        }

        return categoryRepository.findOne(id);
    }

    @Override
    public void deleteOne(Category category) {
        if (StringUtils.isEmpty(category.getId())) {
            logger.info("id为空 不能被删除" + category.getId());
        }
        if (ObjectUtils.isEmpty(this.selectOne(category.getId()))) {
            logger.info("未查询到该数据 删除失败");
            return;
        }
        logger.info("删除的对象为" + category);
        categoryRepository.delete(category);
    }

    @Override
    public List<Category> selectByLevelAndPid(int level, int pid) {
        if (level < CategoryConfig.CATEGORY_LEVEL_GRAND) {
            logger.warn("级别不能小于" + CategoryConfig.CATEGORY_LEVEL_GRAND + " 请重新检查" + level);
            level = CategoryConfig.CATEGORY_LEVEL_GRAND;
        }
        if (pid < CategoryConfig.CATEGORY_PID_MIN_COUNT) {
            pid = CategoryConfig.CATEGORY_LEVEL_GRAND;
            logger.warn("pid 不能小于" + CategoryConfig.CATEGORY_PID_MIN_COUNT + " 请重新检查" + pid);
        }
        List<Category> list = categoryRepository.findByPIdAndLevel(pid, level);
        logger.info("查询到的结果为" + list);
        return list;
    }

    @Override
    public List<Category> selectByLevel(int level) {

        if (level < 0) {
            logger.info("查询的级别不能小于0" + level);
            return null;
        }

        List<Category> list = categoryRepository.findByLevel(level);

        logger.info("查询到的数据为" + list);
        return list;

    }
}
